package level4.tools.operators
{
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.ui.Mouse;
	import flash.ui.MouseCursor;

	/**
	 * 使用鼠标进行拖拽背景滚屏
	 * */
	public class MouseDragger
	{
		private var oldX:int = 0;
		private var oldY:int = 0;
		
		private var scrollDo2d:DisplayObject; 	//滚动的对象
		private var dragDo2d:DisplayObject; 	//拖拽的对象
		/**移动期间要执行的方法*/
		public var mouseMovingFun:Function;
		public var mouseDownFun:Function;
		public var mouseUpFun:Function;
		
		public function MouseDragger(scrollDo2d:DisplayObject,dragDo2d:DisplayObject)
		{
			dragDo2d.addEventListener(MouseEvent.MOUSE_DOWN,onDown);
			this.dragDo2d = dragDo2d;
			this.scrollDo2d = scrollDo2d;
		}
		
		private function onDown(e:MouseEvent):void{
			oldX = e.stageX;
			oldY = e.stageY;
			e.target.stage.addEventListener(MouseEvent.MOUSE_MOVE,onMove);
			e.target.stage.addEventListener(MouseEvent.MOUSE_UP,onUp);
			
			if(mouseDownFun != null){
				mouseDownFun();
			}
			
			Mouse.cursor = MouseCursor.HAND;
		}
		private function onUp(e:MouseEvent):void{
			
			e.target.stage.removeEventListener(MouseEvent.MOUSE_UP,onUp);
			e.target.stage.removeEventListener(MouseEvent.MOUSE_MOVE,onMove);
			
			oldX = oldY = 0;
			
			if(mouseUpFun != null){
				mouseUpFun();
			}
			
			Mouse.cursor = MouseCursor.ARROW;
		}
		private function onMove(e:MouseEvent):void{
			var nx:int = e.stageX - oldX;
			var ny:int = e.stageY - oldY;
			
			//移动
			scrollDo2d.x += nx;
			scrollDo2d.y += ny;
			//更新 记录点
			oldX += nx;
			oldY += ny;
			//边界检测
//			checkBounds();
			checkLargeBg();
			if(mouseMovingFun != null){
				mouseMovingFun();
			}
		}
		/**
		 * 检测边界.
		 * */
		private function checkBounds():void{
			var scrollHalfWidth:int = scrollDo2d.width * .5;
			var scrollHalfHeight:int = scrollDo2d.height * .5;
			//x
			if(scrollDo2d.x < 0 ){
				scrollDo2d.x = 0;
			}else if(scrollDo2d.x > scrollDo2d.stage.stageWidth - scrollHalfWidth){
				scrollDo2d.x = scrollDo2d.stage.stageWidth - scrollHalfWidth;
			}
			//y
			if(scrollDo2d.y < 0 ){
				scrollDo2d.y = 0;
			}else if(scrollDo2d.y + scrollHalfHeight > scrollDo2d.stage.stageHeight){
				scrollDo2d.y = scrollDo2d.stage.stageHeight - scrollHalfHeight;
			}
		}
		/**
		 * scrollDo2d,背景大过 舞台视口
		 * */
		private function checkLargeBg():void{
			var scrollWidth:int = scrollDo2d.width;
			var scrollHeight:int = scrollDo2d.height;
			//x
			if(scrollDo2d.x > 0 ){
				scrollDo2d.x = 0;
			}else if(scrollDo2d.x < scrollDo2d.stage.stageWidth - scrollWidth){
				scrollDo2d.x = scrollDo2d.stage.stageWidth - scrollWidth;
			}
			//y
			if(scrollDo2d.y > 0 ){
				scrollDo2d.y = 0;
			}else if(scrollDo2d.y < scrollDo2d.stage.stageHeight - scrollHeight){
				scrollDo2d.y = scrollDo2d.stage.stageHeight - scrollHeight;
			}
		}
	}
}